package models

import (
	"errors"
	"time"

	"gorm.io/gorm"
)

type Customer struct {
	ID        uint           `json:"id" gorm:"primaryKey"`
	Name      string         `json:"name" gorm:"size:50;not null" binding:"required"`
	Phone     string         `json:"phone" gorm:"size:20;not null" binding:"required"`
	Wechat    string         `json:"wechat" gorm:"size:50"`
	Address   string         `json:"address" gorm:"size:255"`
	Age       int            `json:"age"`
	Gender    string         `json:"gender" gorm:"type:enum('male','female')"`
	City      string         `json:"city" gorm:"size:50;not null" binding:"required"`
	Subject   string         `json:"subject" gorm:"size:50;not null" binding:"required"`
	Grade     string         `json:"grade" gorm:"size:20"`
	Notes     string         `json:"notes" gorm:"type:text"`
	Status    string         `json:"status" gorm:"type:enum('interested','signed_up','enrolled','invalid');default:'interested'"`
	IsPushed  bool           `json:"is_pushed" gorm:"default:false;comment:是否已推送"`
	CreatedBy uint           `json:"created_by" gorm:"not null"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`

	// 关联
	Creator     User         `json:"creator" gorm:"foreignKey:CreatedBy"`
	PushRecords []PushRecord `json:"push_records" gorm:"foreignKey:CustomerID"`
}

// TableName 指定表名
func (Customer) TableName() string {
	return "customers"
}

// BeforeCreate 创建前钩子
func (c *Customer) BeforeCreate(tx *gorm.DB) error {
	if c.Status == "" {
		c.Status = "interested"
	}
	return nil
}

// GetStatusText 获取状态文本
func (c *Customer) GetStatusText() string {
	statusMap := map[string]string{
		"interested": "有意向",
		"enrolled":   "已报名",
		"signed_up":  "已签约",
		"invalid":    "无效客户",
	}
	if text, ok := statusMap[c.Status]; ok {
		return text
	}
	return "未知状态"
}

// GetGenderText 获取性别文本
func (c *Customer) GetGenderText() string {
	genderMap := map[string]string{
		"male":   "男",
		"female": "女",
	}
	if text, ok := genderMap[c.Gender]; ok {
		return text
	}
	return "未知"
}

// CanPush 检查是否可以推送
func (c *Customer) CanPush() bool {
	return c.Status == "interested"
}

// UpdateStatus 更新客户状态
func (c *Customer) UpdateStatus(db *gorm.DB, status string) error {
	if !c.isValidStatus(status) {
		return errors.New("无效的客户状态")
	}
	c.Status = status
	return db.Save(c).Error
}

// isValidStatus 验证状态是否有效
func (c *Customer) isValidStatus(status string) bool {
	switch status {
	case "interested", "signed_up", "enrolled", "invalid":
		return true
	}
	return false
}

// MarkAsPushed 标记客户为已推送
func (c *Customer) MarkAsPushed(db *gorm.DB) error {
	c.IsPushed = true
	return db.Save(c).Error
}
